import { useState } from "react"
import { useNavigate } from "react-router-dom"
import "./NewThreadPage.css"
import { createPostService } from "../api/CommunityApi"

function NewThreadPage() {
  const tags = [
    { id: 1, name: "动漫"},
    { id: 2, name: "面经" },
    { id: 3, name: "游戏" },
    { id: 4, name: "其它" }
  ]
  const navigate = useNavigate()
  const [title, setTitle] = useState("")
  const [content, setContent] = useState("")
  const [image, setImage] = useState(null)
  const [imageFile, setImageFile] = useState(null)
  const [imagePreview, setImagePreview] = useState(null)
  const [tag, setTag] = useState("动漫")
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleImageUpload = (e) => {
    const file = e.target.files[0]
    if (file) {
      if (file.size > 500 * 1024) {
        alert("图片大小不能超过500KB")
        return
      }
      setImageFile(file)
      setImagePreview(URL.createObjectURL(file))
    }
  }

  const handleRemoveImage = () => {
    setImageFile(null)
    setImagePreview(null)
  }

  const handlePost = async () => {
    if (title.trim() === "" || content.trim() === "") {
      alert("请填写标题和内容")
      return
    }

    setIsSubmitting(true)

    try {
      const formData = new FormData()
      formData.append(
        "postBO",
        new Blob(
          [JSON.stringify({
            forumId: tags.find((t) => t.name === tag)?.id || 1,
            title,
            content,
          })],
          { type: "application/json" }
        )
      )
      if (imageFile) {
        formData.append("file", imageFile)
      }
      // 调用API提交帖子
      const response = await createPostService(formData);
      if (response.success) {
        alert("帖子发布成功！")
      } else {
        alert(`发布帖子失败: ${response.message || "未知错误"}`)
        console.error("发布帖子失败:", response)
        return
      }
    } catch (error) {
      console.error("发布帖子失败:", error)
      alert("发布帖子失败，请稍后再试。")
      return
    } finally {
      setIsSubmitting(false)
      navigate("/community")
    }
  };

  const handleCancel = () => {
    if (title || content || image) {
      if (window.confirm("确定要取消吗？未保存的内容将丢失。")) {
        navigate("/community")
      }
    } else {
      navigate("/community")
    }
  }

  return (
    <div className="new-thread-page">
      <div className="page-header">
        <div className="header-content">
          <h1 className="page-title">
            <span className="title-icon">✏️</span>
            发布新帖子
          </h1>
          <p className="page-subtitle">分享你的想法和见解</p>
        </div>
      </div>

      <div className="form-container">
        <div className="form-card">
          <div className="form-section">
            <label className="form-label">
              <span className="label-icon">🏷️</span>
              选择板块
            </label>
            <div className="select-wrapper">
              <select value={tag} onChange={(e) => setTag(e.target.value)} className="form-select">
                <option value="动漫">🎌 动漫</option>
                <option value="面经">💼 面经</option>
                <option value="游戏">🎮 游戏</option>
                <option value="其它">📝 其它</option>
              </select>
            </div>
          </div>

          <div className="form-section">
            <label className="form-label">
              <span className="label-icon">📝</span>
              帖子标题
            </label>
            <input
              type="text"
              placeholder="请输入一个吸引人的标题..."
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="form-input title-input"
              maxLength={100}
            />
            <div className="char-count">{title.length}/100</div>
          </div>

          <div className="form-section">
            <label className="form-label">
              <span className="label-icon">📄</span>
              帖子内容
            </label>
            <textarea
              placeholder="分享你的想法、经验或问题..."
              value={content}
              onChange={(e) => setContent(e.target.value)}
              className="form-textarea"
              maxLength={2000}
            />
            <div className="char-count">{content.length}/2000</div>
          </div>

          <div className="form-section">
            <label className="form-label">
              <span className="label-icon">🖼️</span>
              添加图片 <span className="optional">(可选)</span>
            </label>

            {!imagePreview ? (
              <div className="upload-area">
                <input
                  type="file"
                  accept="image/*"
                  onChange={handleImageUpload}
                  className="file-input"
                  id="image-upload"
                />
                <label htmlFor="image-upload" className="upload-label">
                  <div className="upload-icon">📷</div>
                  <div className="upload-text">
                    <span className="upload-main">点击上传图片</span>
                    <span className="upload-sub">支持 JPG、PNG、GIF，最大500KB</span>
                  </div>
                </label>
              </div>
            ) : (
              <div className="image-preview">
                <div className="preview-header">
                  <span className="preview-title">图片预览</span>
                  <button type="button" onClick={handleRemoveImage} className="remove-image-btn">
                    ✕
                  </button>
                </div>
                <div className="preview-container">
                  <img src={imagePreview} alt="Preview" className="preview-image" />
                </div>
              </div>
            )}
          </div>

          <div className="form-actions">
            <button type="button" onClick={handleCancel} className="btn btn-secondary" disabled={isSubmitting}>
              取消
            </button>
            <button
              onClick={handlePost}
              className={`btn btn-primary ${isSubmitting ? "loading" : ""}`}
              disabled={isSubmitting}
            >
              {isSubmitting ? (
                <>
                  <span className="btn-spinner"></span>
                  发布中...
                </>
              ) : (
                <>
                  <span className="btn-icon">🚀</span>
                  发布帖子
                </>
              )}
            </button>
          </div>
        </div>

        <div className="tips-card">
          <h3 className="tips-title">💡 发帖小贴士</h3>
          <ul className="tips-list">
            <li>选择合适的板块，让更多人看到你的帖子</li>
            <li>标题要简洁明了，突出重点</li>
            <li>内容详细具体，方便他人理解</li>
            <li>添加相关图片可以让帖子更生动</li>
            <li>遵守社区规则，友善交流</li>
          </ul>
        </div>
      </div>
    </div>
  )
}

export default NewThreadPage
